package com.honeywen.mymvc.leetcode;

/**
 * 160. 相交链表
 * https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
 * @author wangwei
 * @date 2019/4/17
 */
public class IntersectionNodeTest {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(1);
        ListNode node3 = new ListNode(8);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        ListNode node6 = new ListNode(5);
        ListNode node7 = new ListNode(0);
        ListNode node8 = new ListNode(1);

        node1.next = node2;
        node2.next= node3;
        node3.next = node4;
        node4.next = node5;

        node6.next = node7;
        node7.next = node8;
        node8.next = node3;

        ListNode a = node1;
        ListNode b = node6;

        System.out.println(getIntersectionNode(a, b));




    }

    public static ListNode getIntersectionNode2(ListNode headA, ListNode headB) {

        int lenA = getLength(headA);
        int lenB = getLength(headB);

        if (lenA == 0 || lenB == 0) {
            return null;
        }

        if (lenA < lenB) {
            // swap
            ListNode tmp = headA;
            headA = headB;
            headB = tmp;

        }

        for (int i = 0; i < Math.abs(lenA - lenB); i++) {
            headA = headA.next;
        }

        while (headA != headB) {
            headA = headA.next;
            headB = headB.next;
        }


        return headA;


    }

    private static int getLength(ListNode node) {
        if (node == null) {
            return 0;
        }
        int n = 0;
        while (node != null) {
            node = node.next;
            n++;
        }

        return n;

    }

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        ListNode p1 = headA;
        ListNode p2 = headB;

        while (p1 != null) {

            while (p2 != null) {
                if (p1 == p2) {
                    return p1;
                }
                p2 = p2.next;
            }
            p1 = p1.next;
            // 重置p2
            p2 = headB;
        }


        return null;

    }


}
